package edu.vanderbilt.multicast.android;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.vanderbilt.vshare.multicast.SRInputStream;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class MulticastVideoPlayer extends ListActivity {

	String[] metaInfo_;
	ListView videolist;
	StreamingClient sc;
	ArrayAdapter<String>  adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate (Bundle savedInstanceState) {
	
		super.onCreate(savedInstanceState);

		createmeta ();
		readmeta ();
		sc = new StreamingClient ();
		
		if (metaInfo_.length > 0) {
			adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, metaInfo_); 
			setListAdapter (adapter);
			getListView ().setOnItemClickListener (videogridlistener);
		}
		// Get the Android-specific compiled XML parser.
	}

	private OnItemClickListener videogridlistener = new OnItemClickListener () {
		
		SRInputStream stream;
		
		void OnItemClickListener ()
		{
			stream = new SRInputStream();
			stream.listen("228.5.6.8");
		}
		
		public void onItemClick (AdapterView parent, View v, int position,
				long id) {			
			String filename = adapter.getItem (position);
			receivefile (filename);
			Log.e ("XMLReader", "Filename="+filename);
			Intent intent = new Intent (MulticastVideoPlayer.this, VideoViewer.class);
			intent.putExtra ("videofilename", filename);
			//startActivity (intent); 
		}
		
		void receivefile (String filename) {
			
			byte[] sample_file = stream.read (filename);

			try {
				File root = Environment.getExternalStorageDirectory ();
				if (root.canWrite ()) {

					File videofile;
					FileOutputStream writer;

					videofile = new File (root, filename);
					if (!videofile.exists ()) {
						writer = new FileOutputStream (videofile);
						writer.write (sample_file);
						writer.close ();
						System.out.println ("Written " + filename
								+ " to sdcard");
					}
				}
			} catch (IOException e) {
				Log.e ("XMLReader", "Could not write file " + e.getMessage ());
			}
		}

	};

	void createmeta () {
		StringBuffer bf = new StringBuffer ();
		bf.append ("<files>\n");
		bf.append ("<file>\n");
		bf
				.append ("<id>1</id>\n<name>documentariesandyou.mp4</name><type>mpeg4</type>\n<length>35006</length>\n");
		bf.append ("</file>\n");
		bf.append ("<file>\n");
		bf
				.append ("<id>2</id>\n<name>sample.3gp</name><type>3gp</type>\n<length>80000</length>\n");
		bf.append ("</file>\n");
		bf.append ("</files>");

		try {
			File root = Environment.getExternalStorageDirectory ();
			if (root.canWrite ()) {
				File meta = new File (root, "meta");
				FileWriter metawriter = new FileWriter (meta);
				BufferedWriter out = new BufferedWriter (metawriter);
				out.write (bf.toString ());
				out.close ();
				metawriter.close ();
			}
		} catch (IOException e) {
			Log.e ("XMLReader", "Could not write file " + e.getMessage ());
		}

	}

	void readmeta () {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder ();
		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace ();
		}
		try {
			File root = Environment.getExternalStorageDirectory ();
			doc = db.parse (new File (root, "meta"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace ();
		}

		NodeList filelist = doc.getElementsByTagName ("file");
		int size = filelist.getLength ();
		metaInfo_ = new String[size];

		for (int i = 0; i < size; i++) {
			Node firstNode = filelist.item (i);

			if (firstNode.getNodeType () == Node.ELEMENT_NODE) {

				String type_s;
				Element element = (Element) firstNode;

				NodeList typeElementList = element
						.getElementsByTagName ("type");
				Element typeElement = (Element) typeElementList.item (0);
				NodeList type = typeElement.getChildNodes ();
				type_s = type.item (0).getNodeValue ();

				if (type_s.equalsIgnoreCase ("mpeg4")
						|| type_s.equalsIgnoreCase ("3gp")) {

					NodeList nameElementList = element
							.getElementsByTagName ("name");
					Element nameElement = (Element) nameElementList.item (0);
					NodeList name = nameElement.getChildNodes ();
					metaInfo_[i] = name.item (0).getNodeValue ();
				}
			}
		}
	}
}
